<template>
  <div class="search-box">
    <form action="/" class="header-search">
      <van-search v-model="searchText" show-action
        background="#3296fa"
        placeholder="请输入搜索关键词" @search="onSearch"
        @cancel="$router.go(-1)"
        @focus="isShowSearch=false" />
    </form>
    <search-results :value="searchText"
      v-if="isShowSearch" />
    <search-history @search="onSearch"
      @clearHistory="clearSearchList"
      :history="searchList"
      v-else-if="!searchText" />
    <search-suggestion v-else :value="searchText"
      @search="onSearch" />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResults from './components/search-results.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import { setItem, getItem } from '@/utils/storage.js'
const HMTT_HISTORY = 'hmtt-history'
export default {
  name: 'search',
  data () {
    return {
      searchText: '',
      isShowSearch: false,
      searchList: getItem(HMTT_HISTORY) || []
    }
  },
  methods: {
    clearSearchList () {
      this.searchList = []
    },
    onSearch (val) {
      // const index = this.searchList.findIndex(item => item === val)
      // if (index !== -1) {
      //   this.searchList.splice(index, 1)
      // }
      // this.searchList.unshift(val)
      if (val.trim().length === 0) {
        return
      }
      this.searchList.unshift(val)
      this.searchList = [...new Set(this.searchList)]
      this.searchText = val
      this.isShowSearch = true
    },
    onCancel () {
      console.log('取消')
    }
  },
  computed: {},
  watch: {
    searchList (nval) {
      setItem(HMTT_HISTORY, nval)
    }
  },
  filters: {},
  components: {
    SearchHistory,
    SearchResults,
    SearchSuggestion
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.search-box {
  .header-search {
    position: sticky;
    top: 0;
    z-index: 2;
  }
  .van-search__action {
    color: #fff;
  }
}
</style>
